package de.tabuma.soapforms;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.util.logging.*;

import de.tabuma.soapforms.soapproject.entity.*;
import de.tabuma.soapforms.soapproject.logik.*;
import de.tabuma.formcreator.entity.*;
import de.tabuma.formcreator.logik.*;
import de.tabuma.soap.*;
import de.tabuma.soap.entity.wsdl.*;
import de.tabuma.soap.logik.*;
import de.tabuma.shopping.logik.LicenseUseFacade;
import com.google.appengine.api.quota.QuotaService;
import com.google.appengine.api.quota.QuotaServiceFactory;


/**
 * 
 * @author alefen
 */
public class soapform extends HttpServlet {

    private final static Logger log = Logger.getLogger(soapform.class.getName());

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

            log.fine("Getting request");

            int soapProjectId = 0;
            if(request.getParameter(constants.soapProjectId)!=null) {
                soapProjectId = Integer.valueOf(request.getParameter(constants.soapProjectId));
            }
            
            log.fine("soapProjectId = "+soapProjectId);

            if(soapProjectId!=0) {
                log.fine("loading project");
                SoapProject soapProject = SoapProjectFacade.get(soapProjectId);
                LicenseUseFacade.create(soapProject.getId().intValue(), "SOAP " + soapProject.getName(), constants.SOAP_FORM_LICENSE, constants.SOAP_FORM_LICENSE, request.getRemoteHost()+"/"+request.getRemoteAddr());
                if(soapProject!=null) {

                    log.fine("loading wsdl file from project");
                    //1. Schritt laden der Url
                    TDefinitions wsdl = de.tabuma.soap.logik.PMF.get(soapProject.getWsdlId(), new TDefinitions());

                    log.fine("loading formular manager");
                    //2. Schritt Initialisierung des FormularManagers
                    FormManager formularManager = FormManagerFactory.createFormularManager(wsdl, soapProject.getMethod());

                    log.fine("getting css links");
                    //3. Ausgabe des XForm Dokuments
                    String cssLink = (String) request.getParameter(constants.cssName);
                    if(cssLink==null) {
                        cssLink = "style.css";
                    }

                     QuotaService qs = QuotaServiceFactory.getQuotaService();
                    long start = qs.getCpuTimeInMegaCycles();


                    log.fine("printing formular content");
                    if(request.getParameter(constants.frameName)==null) {
                        out.println(FormManagerFacade.getXForm(request, formularManager, "soapdata", "parent.iframeName" , cssLink, soapProject.getWsdlId() , soapProject.getMethod()));
                    }
                    else {
                        out.println(FormManagerFacade.getXForm(request, formularManager, "soapdata", "parent."+request.getParameter(constants.frameName)+".iframeName" , cssLink, soapProject.getWsdlId() , soapProject.getMethod()));
                    }

                    long end = qs.getCpuTimeInMegaCycles();

                    double cpuSeconds = qs.convertMegacyclesToCpuSeconds(end - start);
                    log.warning("cpu-time:"+cpuSeconds);
                    
                }
                else {
                    out.println("No project found for parameter <i>" + constants.soapProjectId + "="+soapProjectId+"</i> .");
                }
            }
            else {
                out.println("No parameter <i>" + constants.soapProjectId + "</i> found.");
            }
        }
        catch(Exception e) {
            out.println("Error.");
            log.warning(e.getMessage()+"/"+e.getCause()+"/"+e.getClass());
            String warning = "";
            for(int i=0;i<e.getStackTrace().length;i++) {
                warning += e.getStackTrace()[i]+"\n";
            }
            log.warning(warning);

        }
        finally {
            out.close();
        }
    }
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}